package com.fl.nj.rule;

import lombok.Data;

import java.util.List;

/**
 * 数据获取规则类
 * 用于定义从数据库获取数据的规则
 */
@Data
public class DataFetchRule {
    private String tableName;
    private List<String> columns;
    private String whereClause;
    private String orderBy;
    private int limit;
    private String sql;

    /**
     * 构建SQL查询语句
     * @return SQL查询语句
     */
    public String buildSql() {
        if (sql != null && !sql.trim().isEmpty()) {
            return sql;
        }

        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("SELECT ");

        // 添加列名
        if (columns != null && !columns.isEmpty()) {
            sqlBuilder.append(String.join(", ", columns));
        } else {
            sqlBuilder.append("*");
        }

        // 添加表名
        sqlBuilder.append(" FROM ").append(tableName);

        // 添加WHERE条件
        if (whereClause != null && !whereClause.trim().isEmpty()) {
            sqlBuilder.append(" WHERE ").append(whereClause);
        }

        // 添加ORDER BY
        if (orderBy != null && !orderBy.trim().isEmpty()) {
            sqlBuilder.append(" ORDER BY ").append(orderBy);
        }

        // 添加LIMIT
        if (limit > 0) {
            sqlBuilder.append(" LIMIT ").append(limit);
        }

        return sqlBuilder.toString();
    }
}